package org.example.config;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.example.exception.CusAuthenticationException;
import org.example.handler.GlobalExceptionHandler;
import org.example.model.entity.UserDO;
import org.example.model.vo.LoginUser;
import org.example.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Date;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        if (requestURI.endsWith("/user/login")) {
            filterChain.doFilter(request, response);
            return;
        }
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            Claims claims = JwtUtil.parseJWT(token);
            if (claims == null) {
                throw new CusAuthenticationException("token无效");
            }
            if (isExpired(claims)) {
                throw new CusAuthenticationException("token已过期");
            }

            if (isLogOut(token)) {
                throw new GlobalExceptionHandler.BusinessException(
                        "sys:user:logout",
                        "登出,请重新登录");
            }
            String subject = claims.getSubject();
            LoginUser loginUser = JSONUtil.toBean(subject, LoginUser.class);
            request.setAttribute("loginUser", loginUser);


            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            // 刷新token
            if (isNeedRefresh(claims)) {
                response.addHeader("xs-refresh-token", JwtUtil.createJWT(JSONUtil.toJsonStr(loginUser)));
            }
            filterChain.doFilter(request, response);
        } else {
            throw new CusAuthenticationException("token无效");
        }
    }

    private boolean isLogOut(String token) {
        return Boolean.FALSE.equals(stringRedisTemplate.hasKey("token:" + token));
    }

    private boolean isNeedRefresh(Claims claims) {
        Date expiration = claims.getExpiration();
        Date refreshTime = new Date(expiration.getTime() - 1000 * 60 * 30L);
        return refreshTime.before(new Date());
    }

    private boolean isExpired(Claims claims) {
        Date expiration = claims.getExpiration();
        return expiration.before(new Date());
    }
}
